// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include <unordered_map>
#include "commoncppproblem219.h"

using namespace std;
// @before-stub-for-debug-end
/*
 * @FilePath: \undefinedc:\Users\sxjct\.leetcode\219.存在重复元素-ii.cpp
 * @Brief: 
 * @Version: 1.0
 * @Date: 2021-04-08 16:18:51
 * @Author: tianyiyi
 * @Copyright: Copyright@tianyiyi
 * @LastEditors: Mr.Tian
 * @LastEditTime: 2021-04-08 16:30:53
 */
/*
 * @lc app=leetcode.cn id=219 lang=cpp
 *
 * [219] 存在重复元素 II
 */

// @lc code=start
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> window;
        
        int left = 0;
        int right = 0;
        while (right < nums.size())
        {
            // c 是需要进窗口的元素
            int c = nums[right];

            // 窗口右移
            right++;

            // 判断是否满足条件
            if(window[c] > 0)
            {
                return true;
            }
            window[c]++;

            //窗口左移
            if(right - left > k)
            {
                // d为最左边元素
                int d = nums[left];

                // 左边窗口收缩
                left++;

                // 删除最左边元素
                window[d]--;
            }
        }
        return false;
        
    }
};
// @lc code=end

